<template>
	<view class="edit-page">
		<view class="card">
			<view class="avatar-row">
				<image :src="previewAvatar" mode="aspectFill" class="avatar" />
				<button class="change-btn" @tap="chooseAvatar">更换头像</button>
			</view>
			<view class="field">
				<text class="label">昵称</text>
				<input class="input" type="text" v-model="nickName" placeholder="请输入昵称" />
			</view>
			<!-- 添加性别选择 -->
			<view class="field">
				<text class="label">性别</text>
				<picker class="picker" mode="selector" :range="genderRange" @change="onGenderChange" :value="genderIndex">
					<view class="picker-value">{{ genderRange[genderIndex] }}</view>
				</picker>
			</view>
		</view>
		<view class="footer">
			<button class="save-btn" @tap="handleSave">保存</button>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted } from 'vue'
	import userManager from '@/common/utils/user.js'
	import UpdataUser from '@/api/UpdataUser.js'

	const currentUser = userManager.getUserInfo() || {}
	const userId = ref(currentUser.userId || '')
	const nickName = ref(currentUser.nickName || '')
	const avatarUrl = ref(currentUser.avatarUrl || '')
	const gender = ref(currentUser.gender !== undefined ? currentUser.gender : 0) // 0: 未知, 1: 男, 2: 女
	const newAvatarPath = ref('') // 本地新选择的头像临时路径
	
	// 性别选项
	const genderRange = ['未知', '男', '女']
	const genderIndex = computed(() => {
		// 确保返回有效的索引值
		const index = gender.value
		return index >= 0 && index < genderRange.length ? index : 0
	})

	const previewAvatar = computed(() => newAvatarPath.value || avatarUrl.value || '/static/images/user-avatar.png')
	
	const onGenderChange = (e) => {
		const selectedIndex = e.detail.value
		gender.value = selectedIndex
	}
	
	const chooseAvatar = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				if (res.tempFilePaths && res.tempFilePaths.length > 0) {
					newAvatarPath.value = res.tempFilePaths[0]
					console.log('选择的头像路径:', res.tempFilePaths[0])
				}
			},
			fail: (err) => {
				console.error('选择图片失败:', err)
				uni.showToast({ title: '选择图片失败: ' + (err.errMsg || err.message || '未知错误'), icon: 'none' })
			}
		})
	}

	const handleSave = async () => {
		if (!nickName.value) {
			uni.showToast({ title: '请填写昵称', icon: 'none' })
			return
		}
		if (!userId.value) {
			uni.showToast({ title: '请先登录', icon: 'none' })
			return
		}

		uni.showLoading({ title: '保存中...' })
		try {
			let latestAvatarUrl = avatarUrl.value
			if (newAvatarPath.value) {
				// 上传头像，获取URL
				console.log('开始上传头像:', newAvatarPath.value)
				const uploadRes = await UpdataUser.uploadAvatar(newAvatarPath.value)
				console.log('上传头像响应:', uploadRes)
				if (uploadRes && uploadRes.data && uploadRes.data.code === 200) {
					latestAvatarUrl = uploadRes.data.data
					console.log('头像上传成功，URL:', latestAvatarUrl)
				} else {
					const errorMsg = (uploadRes && uploadRes.data && (uploadRes.data.message || uploadRes.data.msg)) || '头像上传失败'
					throw new Error(errorMsg)
				}
			}
			
			const updateData = {
				userId: userId.value,
				nickName: nickName.value,
				avatarUrl: latestAvatarUrl,
				gender: gender.value
			}
			
			console.log('开始更新用户信息:', updateData)
			const res = await UpdataUser.updateUserInfo(updateData)
			console.log('更新用户信息响应:', res)
			
			if (res && res.data && res.data.code === 200) {
				// 更新本地缓存并通知其他页面刷新
				userManager.updateUserInfo({ 
					nickName: nickName.value, 
					avatarUrl: latestAvatarUrl,
					gender: gender.value 
				})
				uni.$emit('loginStatusChanged', true)
				uni.showToast({ title: '保存成功', icon: 'success' })
				setTimeout(() => uni.navigateBack(), 800)
			} else {
				const errorMsg = (res && res.data && (res.data.message || res.data.msg)) || '保存失败'
				throw new Error(errorMsg)
			}
		} catch (e) {
			console.error('保存失败:', e)
			uni.showToast({ title: e.message || '保存异常', icon: 'none', duration: 3000 })
		} finally {
			uni.hideLoading()
		}
	}
	
	// 页面加载时初始化数据
	onMounted(() => {
		if (!userId.value) {
			// 如果未登录，提示并返回
			uni.showToast({ title: '请先登录', icon: 'none' })
			setTimeout(() => uni.navigateBack(), 1000)
		}
	})
</script>

<style scoped>
	.edit-page {
		min-height: 100vh;
		padding: 32rpx;
		background-color: #F5F5F5;
	}

	.card {
		background-color: #FFFFFF;
		border-radius: 24rpx;
		padding: 32rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	}

	.avatar-row {
		display: flex;
		align-items: center;
		gap: 24rpx;
		margin-bottom: 32rpx;
	}

	.avatar {
		width: 140rpx;
		height: 140rpx;
		border-radius: 50%;
		border: 4rpx solid #89CFF0;
	}

	.change-btn {
		background-color: #89CFF0;
		color: #FFFFFF;
		border: none;
		border-radius: 999rpx;
		padding: 18rpx 28rpx;
		font-size: 28rpx;
	}

	.field {
		display: flex;
		align-items: center;
		padding: 16rpx 0;
		border-top: 1px solid #F0F0F0;
	}

	.label {
		width: 160rpx;
		color: #666666;
		font-size: 28rpx;
	}

	.input, .picker {
		flex: 1;
		font-size: 28rpx;
		padding: 12rpx 16rpx;
		background: #FAFAFA;
		border-radius: 12rpx;
	}
	
	.picker-value {
		color: #333;
		line-height: 1.5;
	}

	.footer {
		margin-top: 48rpx;
	}

	.save-btn {
		width: 100%;
		background-color: #00C853;
		color: #FFFFFF;
		border: none;
		border-radius: 999rpx;
		padding: 24rpx;
		font-size: 30rpx;
		font-weight: bold;
	}
</style>